package com.bomb.voice.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.ImageView;
import android.widget.Toast;

import com.orhanobut.logger.Logger;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import static android.R.attr.path;

/**
 * Created by heyue on 16/7/7.
 */
public class Img2AlbumUtil {
    private static final String TAG = "Img2AlbumUtil";
    public  void saveImg(Context context, ImageView mshowpicture, String imagename) {
        mshowpicture.buildDrawingCache();

        Bitmap bitmap=mshowpicture.getDrawingCache();
        //将Bitmap 转换成二进制，写入本地

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG , 100 , stream);
        byte[] byteArray = stream.toByteArray();
//        File dir=context.getFilesDir();
        File dir=new File(Environment.getExternalStorageDirectory ().getAbsolutePath()+"/picture" );
        if(!dir.exists()) {
            dir.mkdir();
        }

        File file=new File(dir,"Feeling"+imagename +".png" );
        try {
            FileOutputStream fos=new FileOutputStream(file);
            fos.write(byteArray, 0 , byteArray.length);
            fos.flush();

            //用广播通知相册进行更新相册

            Intent intent = new Intent(Intent. ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            context.sendBroadcast(intent);
            Logger.d("------>通知相册更新成功" );
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }


    public void saveImageToSysAlbum(Context context, Bitmap bmp, String imagename) {

            if (bmp != null) {
                try {
                    ContentResolver cr = context.getContentResolver();
                    String url = MediaStore.Images.Media.insertImage(cr, bmp,
                            String.valueOf(System.currentTimeMillis()), "");
//                    Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                Toast.makeText(context,"fail", Toast.LENGTH_SHORT).show();
            }
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
    }
}
